<template>
  <h1 v-if="isFirstView">输入用户名搜索</h1>
  <p v-else-if="loading">loading...</p>
  <div class="row" v-else-if="users.length">
    <div class="card" v-for="user in users" :key="user.id">
      <a :href="user.html_url" target="_blank">
        <img :src="user.avatar_url" style="width: 100px" />
      </a>
      <p class="card-text">{{ user.login }}</p>
    </div>
  </div>
  <p v-else>暂无数据</p>
</template>

<script>
import axios from "axios";

export default {
  name: "List",
  data() {
    return {
      isFirstView: true,
      loading: false,
      users: [],
    };
  },
  methods: {
    async searchUsers(searchName) {
      // console.log(searchName);
      // 发送请求之前
      this.isFirstView = false;
      this.loading = true;
      // 发送请求，请求users数据
      const response = await axios({
        method: "GET",
        // url: "https://api.github.com/search/users",
        // url: "http://localhost:9527/search/users", // 目标服务器地址
        url: "/api/search/users", // 代理服务器地址
        params: {
          q: searchName,
        },
      });
      // 请求成功了 - 对数据处理
      // map 长度不变，值变
      // filter 长度变，值不变
      this.users = response.data.items.map((user) => ({
        login: user.login,
        html_url: user.html_url,
        avatar_url: user.avatar_url,
        id: user.id,
      }));

      this.loading = false;
    },
  },
  mounted() {
    this.$bus.$on("searchUsers", this.searchUsers);
  },
  beforeDestroy() {
    this.$bus.$off("searchUsers", this.searchUsers);
  },
};
</script>

<style>
.card {
  float: left;
  width: 33.333%;
  padding: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>